#-------------------------------------------------------------------------------
# Name:        模块1
# Purpose:
#
# Author:      Administrator
#
# Created:     27/04/2024
# Copyright:   (c) Administrator 2024
# Licence:     <your licence>
#-------------------------------------------------------------------------------
from PIL import Image
import csv
import os
import platform
import sys
from pathlib import Path
import torch
import os
from PIL import ImageEnhance

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from utils.general import (
    LOGGER,
    Profile,
    check_file,
    check_img_size,
    check_imshow,
    check_requirements,
    colorstr,
    cv2,
    increment_path,
    non_max_suppression,
    print_args,
    scale_boxes,
    strip_optimizer,
    xyxy2xywh,
)
import re
import np
import pytesseract
import subprocess

pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'

def Picture_Synthesis(son_img,
                      coordinate=None):
    """
    :param mother_img: 母图
    :param son_img: 子图
    :param save_img: 保存图片名
    :param coordinate: 子图在母图的坐标
    :return:
    """

    S_Img = Image.open(son_img)

    height,width = S_Img.size
    print('width=',width,'  height=',height)
    width = width+200
    height = height+200
    mother_img= np.ones((width, height, 3), dtype=np.uint8)

    mother_img[:, :, 0] = 255  # 蓝色通道
    mother_img[:, :, 1] = 122    # 绿色通道
    mother_img[:, :, 2] = 0    # 红色通道

    cv2.imwrite('D:\\imagetest\\wwwwwwwww.png', mother_img, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

    #将图片赋值,方便后面的代码调用
    M_Img = Image.open('D:\\imagetest\\wwwwwwwww.png')

    factor = 1#子图缩小的倍数1代表不变，2就代表原来的一半

    #给图片指定色彩显示格式
    M_Img = M_Img.convert("RGBA")  # CMYK/RGBA 转换颜色格式（CMYK用于打印机的色彩，RGBA用于显示器的色彩）

    # 获取图片的尺寸
    M_Img_w, M_Img_h = M_Img.size  # 获取被放图片的大小（母图）
    #print("母图尺寸：",M_Img.size)
    S_Img_w, S_Img_h = S_Img.size  # 获取小图的大小（子图）
    #print("子图尺寸：",S_Img.size)

    size_w = int(S_Img_w / factor)
    size_h = int(S_Img_h / factor)

    # 防止子图尺寸大于母图
    if S_Img_w > size_w:
        S_Img_w = size_w
    if S_Img_h > size_h:
        S_Img_h = size_h

    # # 重新设置子图的尺寸
    # icon = S_Img.resize((S_Img_w, S_Img_h), Image.ANTIALIAS)
    icon = S_Img.resize((S_Img_w, S_Img_h), Image.Resampling.LANCZOS)
    w = int((M_Img_w - S_Img_w) / 2)
    h = int((M_Img_h - S_Img_h) / 2)

    try:
        if coordinate==None or coordinate=="":
            coordinate=(w, h)
            # 粘贴子图到母图的指定坐标（当前居中）
            M_Img.paste(icon, coordinate, mask=None)
        else:
            print("已经指定坐标")
            # 粘贴子图到母图的指定坐标（当前居中）
            M_Img.paste(icon, coordinate, mask=None)
    except:
        print("坐标指定出错 ")
    # 保存图片
    M_Img.save('D:\\imagetest\\eeeeeeeeeeeeeeeeeeeee.png')

    return 'D:\\imagetest\\eeeeeeeeeeeeeeeeeeeee.png'

def DrawRectWithText(screenshot, rect, text='aaa'):
    h, w = screenshot.shape[:2]

    x = int(w*rect[0])   # 起始 x 坐标
    y = int(h*rect[1])  # 起始 y 坐标
    width = int(w*rect[2])  # 感兴趣区域的宽度
    height = int(h*rect[3])  # 感兴趣区域的高度
    return x,y,width,height

def qqq(screenshot,rect,t):
    path='D:\\imagetest\\'
    x,y,w,h=DrawRectWithText(screenshot,rect)

    # 切片裁剪图像
    if(t==1):
        cropped_image = screenshot[y+30:y+120, x-10:x+w]
    else:
        cropped_image = screenshot[y+20:y+70, x:x+w-10]
    cv2.imwrite(path+'-testscreenshot2.png', cropped_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])

def extract_numbers(text):
    result = []
    current_number = ''
    for char in text:
        if char.isdigit():
            current_number += char
        elif current_number:
            result.append(int(current_number))
            current_number = ''
    if current_number:
        result.append(int(current_number))
    return result

def rename_file(old_path, new_name):
    new_path = os.path.join(os.path.dirname(old_path), new_name)
    os.rename(old_path, new_path)

def replace_extension(filename, new_extension):
    # 使用os.path.splitext获取文件名和后缀名
    name, _ = os.path.splitext(filename)
    # 拼接新的文件名和后缀名
    new_filename = name + '.' + new_extension
    return new_filename

def saveimg(d,rect,filename,image_path,t):
    path='D:\\imagetest\\'

    qqq(d,rect,t)

    new_path=Picture_Synthesis(path+'-testscreenshot2.png')

    image=Image.open(new_path)

    # 设置目标图像大小
    target_width = 2*image.width  # 假设提升为原始宽度的两倍
    target_height =2*image.height  # 假设提升为原始高度的两倍
    target_size = (target_width, target_height)
    # 使用双线性插值进行图像分辨率提升
    upscaled_image = image.resize(target_size, 3)
    image_np = np.array(upscaled_image)
    # 转换为灰度图像
    gray_image = cv2.cvtColor(image_np, cv2.COLOR_BGR2BGRA)
    # 应用高斯模糊来进行抗锯齿处理
    blurred_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
    # 图像增强（锐化）来提高清晰度
    kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])  # 定义锐化核
    image_np = cv2.filter2D(blurred_image, -1, kernel)


    # 将NumPy数组传递给OpenCV的cv2.imread函数
    image = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)

    #cv2.imshow('new_im', image)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()

    # 识别文字，并指定语言
    s = pytesseract.image_to_string(image, lang='chi_sim')
    s=s.replace('\n', '').replace('\r', '')
    print('string=',s)
    text=s
    if text!=None:
        extracted_text = re.sub(r'[^\w\s]', '', text)
        extracted_text =extracted_text.rstrip("\n")
        if extracted_text != None:
            cleaned_text = extracted_text.replace(" ", "")
            print(cleaned_text,extract_numbers(file)[0])
            print(file)
            new_extension = "txt"
            # 替换后的文件名
            txt_filename = replace_extension(image_path, new_extension)
            print(txt_filename)  # 输出: "example.csv"
            new_txtfile=cleaned_text+str(extract_numbers(file)[0])+".txt"
            print(new_txtfile)
            try:
                rename_file(image_path, cleaned_text+str(extract_numbers(file)[0])+".png")
                rename_file(txt_filename, new_txtfile)
            except Exception as e:
                result = 'Error: %s' % e+'  '+image_path+'   '+txt_filename
                print(result)
                try:
                    # 删除文件
                    #os.remove(image_path)
                    print(f"文件 '{image_path}' 已成功删除")
                except OSError as e:
                    print(f"删除文件时出错: {e}")
        else:
            print("未找到匹配的内容")
    else:
        print("未找到匹配的内容")

def check_file_size(file_path):
    try:
        file_size = os.path.getsize(file_path)
        return file_size
    except Exception as e:
        print(f"获取文件大小时出现异常: {e}")
        return None

if __name__ == '__main__':
    #directory = 'E:\\ultralytics\\'
    directory = 'D:\\imagetest\\'

    # 列出目录下的所有文件
    files = os.listdir(directory)

    # 打印文件列表
    for file in files:
        file_extension = file.split('.')[-1].lower()
        #print('file_extension=',file_extension)

        if(file_extension!='txt' and file !='-testscreenshot2.png' and file !='eeeeeeeeeeeeeeeeeeeee.png' and file !='wwwwwwwww.png'):
            image_path = directory+file  # 图片路径
            print('image_path=',image_path)

            file_name = os.path.basename(image_path)

            file_size = check_file_size(image_path)

            d =  cv2.imread(image_path)

            if((file_size/1024)>1000):
                saveimg(d,[0.03,0.10,0.94,0.4],file,image_path,1)
            else:
                saveimg(d,[0.03,0.10,0.94,0.4],file,image_path,0)

    # 指定文件夹路径
    folder_path = directory

    # 存储文件名及出现次数的字典
    file_count = {}

    # 遍历文件夹中的文件
    for filename in os.listdir(folder_path):
        # 拼接文件的完整路径
        file_path = os.path.join(folder_path, filename)
        # 如果是文件
        if os.path.isfile(file_path):
            # 去掉文件后缀
            base_filename, file_extension = os.path.splitext(filename)
            # 统计去掉后缀的文件名出现次数
            file_count[base_filename] = file_count.get(base_filename, 0) + 1
    '''
    # 输出文件名少于两次的文件
    for filename, count in file_count.items():
        if count < 2:
            print(f"文件 '{filename}' 出现次数少于两次")
            try:
                # 删除文件
                delfile_path=directory+filename+'.txt'
                os.remove(delfile_path)
                print(f"文件 '{delfile_path}' 已成功删除")
            except OSError as e:
                print(f"删除文件时出错: {e}")
    '''